package kernel;

import java.util.ArrayList;

import org.jivesoftware.smack.Chat;
import org.jivesoftware.smack.ConnectionListener;
import org.jivesoftware.smack.XMPPException;


public class Kernel {
	private ArrayList<ConnectionListener> _connectionListeners;
	
	private GoogleTalkConnection _connection;
	private ArrayList<Chat> _chats;
	
	private static Kernel _kernel;
	
	private Kernel(){
		_connectionListeners = new ArrayList<ConnectionListener>();
		_chats = new ArrayList<Chat>();
	}
	
	public static Kernel getActiveKernel(){
		if(_kernel == null){
			_kernel = new Kernel();
			return _kernel;
		}
		else
			return _kernel;
	}
	
	public void createGoogleTalkConnection(String username, String password) throws XMPPException {
		if (_connection != null) {
			_connection.disconnect();
			for (ConnectionListener listener : _connectionListeners) {
				_connection.removeConnectionListener(listener);
			}
		} else {
			_connection = new GoogleTalkConnection();
			_connection.connect();
			
			for (ConnectionListener listener : _connectionListeners) {
				_connection.addConnectionListener(listener);
			}
			
			
			if (_connection.isConnected()) {
				_connection.login(username, password);
			}
		}
	}
	
	public Chat getChat(String user){
		// Check if there is already a Chat with this user:
		for (Chat chat : _chats) {
			String participant = chat.getParticipant();
			if(user == participant)
				return chat;
		}
		
		if(_connection != null && _connection.isConnected()){
		Chat newChat = _connection.getChatManager().createChat(user, null);
			_chats.add(newChat);
			return newChat;
		} else {
			return null;
		}
	}

	public GoogleTalkConnection getConnection() {
		return _connection;
	}
	
	public void addConnectionListener(ConnectionListener listener){
		if (!_connectionListeners.contains(listener))
			_connectionListeners.add(listener);
	}
	public void removeConnectionListener(ConnectionListener listener){
		if (_connectionListeners.contains(listener))
			_connectionListeners.remove(listener);
	}
}
